package app.controllers.api;

import app.Const;
import app.constant.TransferConstant;
import app.kit.VerifyKit;
import app.models.basic.Notes;
import app.models.member.MemberProduct;
import app.models.transfer.TranferMode;
import app.models.transfer.TransferProduct;
import app.services.auth.AuthInterceptor;
import app.services.auth.AuthParam;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import com.google.common.primitives.Doubles;
import com.jfinal.aop.Before;
import com.jfinal.ext.interceptor.POST;
import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import goja.StringPool;
import goja.date.DateFormatter;
import goja.mvc.Controller;
import org.joda.time.DateTime;

import java.sql.SQLException;
import java.util.Date;
import java.util.Map;

/**
 * <p>
 * The url transfer Controller.
 * </p>
 *
 * @author sagyf yang
 * @version 1.0
 * @since JDK 1.6
 */
public class TransferController extends Controller {

    /**
     * The index route.
     * the url /transfer
     */
    @Before({POST.class, AuthInterceptor.class})
    @AuthParam(auth = true)
    public void index() {
        // 会员ID
        int member_id = getAttrForInt(AuthInterceptor.ATTR_MEMBER_PK);
        // 会员理财ID
        int mp_id = getParaToInt();

        MemberProduct product = MemberProduct.dao.findProductById(mp_id);
        if (product == null) {
            renderAjaxFailure("无法找到购买纪录");
            return;
        }

        String notice = Notes.dao.findByTransfer();

        Map<String, Object> results = Maps.newHashMapWithExpectedSize(2);
        results.put(Const.FIELD_PRODUCT, product);
        results.put("notice", notice);
        renderAjaxSuccess(results);
    }


    /**
     * 申请转让确认
     */
    @Before({POST.class, AuthInterceptor.class})
    @AuthParam(auth = true)
    public void confirm() {

        // 会员ID
        int member_id = getAttrForInt(AuthInterceptor.ATTR_MEMBER_PK);
        // 会员理财ID
        int mp_id = getParaToInt();


        MemberProduct product = MemberProduct.dao.findProductInfoById(mp_id);
        if (product == null) {
            renderAjaxFailure("无法找到购买纪录");
            return;
        }
        // 转让价格
        String price_str = getPara(Const.FIELD_PRICE);
        if (Strings.isNullOrEmpty(price_str) || !VerifyKit.checkDecimals(price_str)) {
            renderAjaxFailure("请输入正确的转让价格");
            return;
        }

        Double price = Doubles.tryParse(price_str);

//        final Member member = getAttr(AuthInterceptor.ATTR_MEMBER);
        Date date = DateTime.now().toDate();

        final TransferProduct transferProduct = new TransferProduct();
        final TranferMode tranferMode = new TranferMode();

        transferProduct.set(Const.FIELD_PRODUCT, product.getNumber("product_id").intValue());
        transferProduct.set("product_name", product.getStr(Const.FIELD_NAME));
        transferProduct.set(Const.FIELD_PRICE, price);
        transferProduct.set(Const.FIELD_YIELD, product.getNumber(Const.FIELD_YIELD).floatValue());
        transferProduct.set("remaining_days", 0);
        transferProduct.set("assignor", member_id);
//        tranferProduct.set("assignor_name", member.getStr(Const.FIELD_NAME));
        transferProduct.set("hold_days", product.getNumber("hold_days").intValue());
        transferProduct.set("handing_charge", 0);
        transferProduct.set("transfer_date", date);
        transferProduct.set("transfer_time", date);
        transferProduct.set(Const.FIELD_CREATE_TIME, date);
        transferProduct.set(Const.FIELD_STATUS, TransferConstant.STATUE_PAUSE);

        tranferMode.set("mode_type", TransferConstant.MOE_PRICE);
        tranferMode.set(Const.FIELD_PRICE, price);
        tranferMode.set("aging", product.getNumber("transfer_aging").intValue());
        tranferMode.set(Const.FIELD_CREATE_TIME, date);

        final boolean tranfer = Db.tx(new IAtom() {
            @Override
            public boolean run() throws SQLException {
                if (transferProduct.save()) {
                    tranferMode.set("tranfer", transferProduct.getLong(StringPool.PK_COLUMN));
                    return tranferMode.save();
                } else {
                    return false;
                }
            }
        });

        if (tranfer) {
            JsonKit.setDatePattern(DateFormatter.YYYY_MM_DD_HH_MM_SS);
            renderAjaxSuccess(transferProduct);
        } else {
            renderAjaxError("转让失败");
        }

    }




}